<?php
class CartsController extends AppController {

	var $name = 'Carts';
	var $uses = array('Cart','Category','User');
	var $permissions = array(
			'add' => array('admin','manag'),
			'index' => '*',
			'view' => '*',
			'edit' => array('admin','manag'),
			'delete' => array('admin','manag'),
			'category_add' => array('admin','manag'),
			'category_delete' => array('admin','manag'),
			'category_edit' => array('admin','manag'),
			'category_index' => array('admin','manag')
	);
	
	function beforeFilter(){
		parent::beforeFilter();
		$this->FileUpload->fileModel('Upload');
		$this->FileUpload->uploadDir(UPLOAD_PATH);
	}
	
	function beforeRender(){
		parent::beforeRender();
		
	}
	
	function index($category_id=null) {
		$joins = array();
		$conditions = array('Cart.controller'=>$this->params['controller'] );
		$order = array('Cart.name');
		
		if ($category_id != null && is_numeric($category_id)) {
			$category = $this->Category->read(null, $category_id);
			array_push($joins, array('table' => 'carts_categories', 'alias' => 'CartsCategory', 'type' => 'INNER', 'conditions' => array( 'CartsCategory.carts_id = Cart.id')));
			array_push($joins, array('table' => 'categories', 'alias' => 'Category', 'type' => 'INNER', 'conditions' => array( 'CartsCategory.category_id = Category.id')));
			$conditions['Category.lft >= '] = $category['Category']['lft'];
			$conditions['Category.rght <= '] = $category['Category']['rght'];			
		}
				
		$this->Cart->recursive = 0;
		$this->paginate = array('conditions'=>$conditions,'joins'=>$joins,'limit'=>21,'order'=>$order);
		$this->set('items', $this->paginate('Cart'));
	}
	
	function category_index() {
		$this->Category->recursive = 0;
		$conditions = array('Category.controller'=>$this->params['controller'] );
		$this->paginate = array('conditions'=>$conditions,'order'=>array("lft"=>"asc"));
		$categories = $this->treeForCombobox( $this->paginate('Category'),'Category',true);
		$this->set('categories', $categories);
	}
	
	function category_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid category', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Category->save($this->data)) {
				$this->Category->updateAll(
				array('Category.parent_id' => 0),
				array('Category.parent_id' => NULL)
				);
				$this->Session->setFlash(__('The category has been saved', true));
				$this->redirect(array('action' => 'category_index'));
			} else {
				$this->Session->setFlash(__('The category could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Category->read(null, $id);
		}
		$conditions = array('Category.controller'=>$this->params['controller'] );
		$parentCategory = $this->Category->find('threaded', array('conditions'=>$conditions));
		$parentCategories = $this->treeForCombobox($parentCategory,'Category');

		$joins = array();
		array_push($joins, array('table' => 'users_categories', 'alias' => 'UsersCategory', 'type' => 'INNER', 'conditions' => array( 'UsersCategory.user_id = User.id')));
		$users_selected = $this->User->find('all',array('conditions'=>array('UsersCategory.category_id'=>$id),'joins'=>$joins));
		
		if(is_array($users_selected) && !empty($users_selected)){
			$users_list = array(); 
			foreach ($users_selected as $key => $u) {
				array_push($users_list, $u['User']['id']);
			}
			if(count($users_list) > 1){
				$users = $this->User->find('all',array('conditions'=>array('User.id NOT '=>$users_list)));
			}else{
				$users = $this->User->find('all',array('conditions'=>array('User.id !='=>$users_list[0])));
			}
		}else{
			$users = $this->User->find('all');
		}
		
		$this->set(compact('parentCategories','users_selected','users'));
	}
	
	function category_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for category', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Category->delete($id)) {
			$this->Session->setFlash(__('Category deleted', true));
			$this->redirect($this->referer());
		}
		$this->Session->setFlash(__('Category was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}	

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid cart', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('item', $this->Cart->read(null, trim($id)));
		$this->Cart->recursive = 0;
		$neighbors = $this->Cart->find('neighbors', array('field' => 'id', 'value' => $id,'ordrt'=>'Cart.name'));
		$this->set('neighbors', $neighbors);
		$this->set('return', $this->referer());
	}
	
	function koszyk_dodaj($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid cart', true));
			$this->redirect($this->referer());
		}
// 		$i = count($this->Session->read('Order'));
		$this->Session->write('Order.'.$id,$id);
		$this->redirect($this->referer());
	}
	
	function koszyk_wyczysc(){
		$this->Session->delete('Order');
		$this->redirect($this->referer());
	}
	
	function koszyk_zamow(){		
		if(!empty($this->data)){
			
			if($this->Session->check('Auth.User.id')){
				if($this->koszyk_wyslij()){
					
					$this->Session->delete('Order');
					$this->redirect('/');
				}else{
					$this->Session->setFlash(__('Bład wysyłania zamówienia. Prosimy o kontakt telefoniczny.', true));
				}
			}else{
				$this->Session->setFlash(__('Proszę się zalogować !', true));
				$this->redirect('/login');
			}
			
		}
		$ids = $this->Session->read('Order');
		if(is_array($ids) && !empty($ids)){
			$items_order = $this->Cart->find('all',array('conditions'=>array('Cart.id'=>$ids)));
		}else{
			$items_order = array();
		}
		$this->set('items_order',$items_order); 
	}

	function koszyk_usun($id=null){
		$this->Session->delete('Order.'.$id);
		$this->redirect($this->referer());
	}
	
	
	private function koszyk_wyslij(){
		 
		$manag = $this->User->find('list',array('fields'=>'email','conditions'=>array('User.group'=>"manag"))); // moderators
		if(is_array($manag) && !empty($manag)){
		}else{
			$manag = $this->User->find('list',array('fields'=>'email','conditions'=>array('User.group'=>"admin")));
		}
		
// 		$this->Email->delivery = 'debug';
		
		$this->Email->to = $manag;
		$this->Email->bcc = 'kowal.sylwester@gmail.com';
		$this->Email->subject = __("Zamówienie z ",true).$_SERVER['HTTP_HOST'];
		$this->Email->from = $this->Auth->user('email')." <{$this->Auth->user('email')}>";
		$this->Email->template = "koszyk-zamowienie";
		$this->Email->sendAs = 'both'; // text; html; both;
	
		//Do not pass any args to send()
		if ( $this->Email->send() ) {
			return true;
		} else {
			return false;
		}
	}

	function add() {
		if(!empty($this->data)){
// 			debug($this->data); die();
			if(isset($this->data['Category']['Category']) && is_array($this->data['Category']['Category']) && count($this->data['Category']['Category']) != 0){
				if($this->FileUpload->success){
					
					$this->data['Cart']['numer'] = substr($this->FileUpload->currentFile['name'], 0, -4);
					$this->data['Cart']['upload_id'] = $this->Cart->Upload->getLastInsertID();
					
				}else{
					$this->Session->setFlash($this->FileUpload->showErrors());
				}
	
				
				$this->data['Cart']['controller'] = $this->params['controller'];
				
				$this->Cart->create();
				if ($this->Cart->save($this->data)) {
					$this->Session->setFlash(__('The cart has been saved', true));
					$this->redirect(array('action' => 'index'));
				} else {
					$this->Session->setFlash(__('The cart could not be saved. Please, try again.', true));
				}
			}else{
				$this->Session->setFlash(__('Zdjęcie nie zostało dodane. Proszę wybrać kategorię.', true));
			}
		}
		$this->Category->recursive = 0;
		$conditions = array('Category.controller'=>$this->params['controller'] );
		$this->paginate = array('conditions'=>$conditions,'order'=>array("lft"=>"asc"),'limit'=>999);
		$categories = $this->treeForCombobox( $this->paginate('Category'),'Category');
		$this->set(compact('categories'));
	}
	
	function category_add() {
		if (!empty($this->data)) {
// 			debug($this->data); die;
			$this->data['Category']['controller'] = $this->params['controller'];
			$this->Category->create();
			if ($this->Category->save($this->data)) {
				$this->Category->updateAll(
				array('Category.parent_id' => 0),
				array('Category.parent_id' => NULL)
				);
				$this->Session->setFlash(__('The category has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The category could not be saved. Please, try again.', true));
			}
		}
		// 		$uploads = $this->Category->Upload->find('list');
		// 		$items = $this->Category->Item->find('list');
		$this->Category->recursive = 0;
		$conditions = array('Category.controller'=>$this->params['controller'] );
		$parentCategory = $this->Category->find('threaded',array('conditions'=>$conditions));
		$parentCategories = $this->treeForCombobox($parentCategory,'Category');
		// 		$this->data['Category']['parent_id'] = (is_null($parent_id)) ? null : $parent_id;
		$users = $this->User->find('all');
		$this->set(compact('parentCategories','users'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid cart', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			
			
			
			if($this->FileUpload->success){
			
				$this->data['Cart']['numer'] = substr($this->FileUpload->currentFile['name'], 0, -4);
				$this->data['Cart']['upload_id'] = $this->Cart->Upload->getLastInsertID();
			
			}else{
				$this->Session->setFlash($this->FileUpload->showErrors());
			}
			
			
			$this->Cart->CartsCategory->deleteAll(array('CartsCategory.carts_id'=>$this->data['Cart']['id']));
			
			if ($this->Cart->save($this->data)) {
				$this->Session->setFlash(__('The cart has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The cart could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Cart->read(null, $id);
		}
		$this->Category->recursive = 0;
		$conditions = array('Category.controller'=>$this->params['controller'] );
		$this->paginate = array('conditions'=>$conditions,'order'=>array("lft"=>"asc"),'limit'=>999);
		$categories = $this->treeForCombobox( $this->paginate('Category'),'Category');
		$this->set(compact('categories'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for cart', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Cart->delete($id)) {
			$this->Session->setFlash(__('Cart deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Cart was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
}
